from pydantic import BaseModel
from fastapi import APIRouter, HTTPException
import service.post as service
from .utils import Result, get_now_time

router = APIRouter(prefix="/post")


class Post(BaseModel):
    id: str = None
    title: str = None
    content: str = None
    time: str = None
    username: str = None


@router.post("/add", status_code=200)
async def add_post(post: Post):
    post = post.model_dump()
    post['time'] = get_now_time()
    service.create_post(post)
    return Result(message="Add post successfully", code=201)


@router.get("/page", status_code=200)
async def get_page(page_number: int, page_size: int, username: str = None):
    posts = service.page(page_number, page_size, username)
    posts = [post.todict() for post in posts]
    total = service.get_total(username)
    return Result(message="Get page successfully", data=posts, total=total, code=203)


@router.put('/update', status_code=200)
async def update_post(post: Post):
    post_data = post.model_dump()
    post_data['time'] = get_now_time()
    if service.update_post(post_data):
        return Result(message="Update post successfully", code=200)
    else:
        raise HTTPException(detail="Post not found", status_code=401)


@router.delete('/del/{id}', status_code=200)
async def del_post(id: str):
    if service.delete_post(id):
        return Result(message="Delete post successfully", code=205)
    else:
        raise HTTPException(detail="Post not found", status_code=401)
